const WebSocket = require('ws');

class BankDataFormatTester {
    constructor() {
        this.ws = null;
        this.testResults = [];
        this.currentTest = null;
    }

    async connect() {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket('ws://localhost:3000');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接已建立');
                resolve();
            });

            this.ws.on('message', (data) => {
                this.handleMessage(data);
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接错误:', error);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
            });
        });
    }

    handleMessage(data) {
        try {
            const message = JSON.parse(data.toString());
            console.log(`📨 接收到消息: ${JSON.stringify(message, null, 2)}`);

            if (this.currentTest && message.act_id === this.currentTest.act_id) {
                this.validateDataFormat(message);
            }
        } catch (error) {
            console.error('❌ 解析消息失败:', error);
        }
    }

    validateDataFormat(message) {
        const { act_id, code, data, msg } = message;

        if (code === 0 && data) {
            // 验证数据格式
            const requiredFields = ['balanceGold', 'balanceMoney', 'gold', 'money'];
            const missingFields = requiredFields.filter(field => !(field in data));

            if (missingFields.length === 0) {
                console.log(`✅ 指令${act_id}数据格式正确:`, data);
                this.addTestResult(`指令${act_id}数据格式`, true, '数据格式符合要求');
            } else {
                console.log(`❌ 指令${act_id}数据格式错误，缺少字段:`, missingFields);
                this.addTestResult(`指令${act_id}数据格式`, false, `缺少字段: ${missingFields.join(', ')}`);
            }
        } else {
            console.log(`⚠️ 指令${act_id}返回错误或没有data字段:`, { code, msg });
        }
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            testName,
            success,
            message,
            timestamp: new Date().toISOString()
        });
    }

    async sendWebSocketMessage(act_id, data = null) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            throw new Error('WebSocket未连接');
        }

        const message = {
            c: act_id,
            d: data
        };

        console.log(`📤 发送消息: ${JSON.stringify(message)}`);
        this.ws.send(JSON.stringify(message));
    }

    async testBankOperations() {
        console.log('\n🏦 开始测试银行操作指令数据格式...\n');

        try {
            // 测试1457：银币从银行取出
            console.log('测试指令1457：银币从银行取出');
            this.currentTest = { act_id: 1457 };
            await this.sendWebSocketMessage(1457, { num: 100, pwd: '123456' });
            await this.delay(2000);

            // 测试1459：银币存入银行
            console.log('\n测试指令1459：银币存入银行');
            this.currentTest = { act_id: 1459 };
            await this.sendWebSocketMessage(1459, { num: 100 });
            await this.delay(2000);

            // 测试1460：金币从银行取出
            console.log('\n测试指令1460：金币从银行取出');
            this.currentTest = { act_id: 1460 };
            await this.sendWebSocketMessage(1460, { num: 100, pwd: '123456' });
            await this.delay(2000);

            // 测试1462：金币存入银行
            console.log('\n测试指令1462：金币存入银行');
            this.currentTest = { act_id: 1462 };
            await this.sendWebSocketMessage(1462, { num: 100 });
            await this.delay(2000);

            // 等待所有响应
            await this.delay(3000);

            // 输出测试结果
            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error);
        }
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.testName}: ${result.message}`);
        });

        const successCount = this.testResults.filter(r => r.success).length;
        const totalCount = this.testResults.length;

        console.log('\n' + '='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);
    }

    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async run() {
        try {
            await this.connect();
            await this.testBankOperations();
        } catch (error) {
            console.error('❌ 测试失败:', error);
        } finally {
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
if (require.main === module) {
    const tester = new BankDataFormatTester();
    tester.run();
}

module.exports = BankDataFormatTester;
